<template>
    <el-card class="mt15 mb15">
        <!-- 第一行 -->
        <div class="search-filter">
            <el-row :gutter="20">
                <el-col :span="6">
                    <sitem label="当前职位：">
                        <el-input
                            slot="item"
                            v-model="listQuery.jobName"
                            placeholder="请输入关键字"
                            @input="handleFilter"
                        />
                    </sitem>
                </el-col>
                <el-col :span="6">
                    <sitem label="姓名：">
                        <el-input
                            slot="item"
                            v-model="listQuery.userName"
                            placeholder="请输入关键字"
                            @input="handleFilter"
                        />
                    </sitem>
                </el-col>
                <el-col :span="6">
                    <sitem label="性别：">
                        <el-select
                            slot="item"
                            v-model="listQuery.sex"
                            placeholder="选择"
                            clearable
                            @change="handleFilter"
                        >
                            <el-option
                                v-for="item in sex"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </sitem>
                </el-col>
                <el-col :span="6">
                    <sitem label="年龄：" range>
                        <el-input
                            slot="low"
                            v-model="listQuery.minAge"
                            oninput="value=value.replace(/[^\d]/g,'')"
                            max-length="9"
                            placeholder="填写整数"
                        />
                        <el-input
                            slot="high"
                            v-model="listQuery.maxAge"
                            oninput="value=value.replace(/[^\d]/g,'')"
                            max-length="9"
                            placeholder="填写整数"
                            @keyup.enter.native="handleFilter"
                        />
                    </sitem>
                </el-col>
                <el-col :span="6">
                    <sitem label="婚姻状况：">
                        <el-select
                            slot="item"
                            v-model="listQuery.maritalStatus"
                            placeholder="选择"
                            clearable
                            @change="handleFilter"
                        >
                            <el-option
                                v-for="item in maritalStatus"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </sitem>
                </el-col>
                <el-col :span="6">
                    <sitem label="工作经验：">
                        <el-select
                            slot="item"
                            v-model="listQuery.experience"
                            placeholder="选择"
                            clearable
                            @change="handleFilter"
                        >
                            <el-option
                                v-for="item in experience"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </sitem>
                </el-col>
                <!-- <el-col :span="6">
                          <sitem label="最高学历：">
                            <el-select
                              slot="item"
                              v-model="listQuery.eduLevel"
                              placeholder="选择"
                              clearable
                              @change="handleFilter"
                            >
                              <el-option
                                v-for="item in eduLevels"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                              />
                            </el-select>
                          </sitem>
                        </el-col> -->
                <el-col :span="6">
                    <sitem label="期望月薪：">
                        <el-select
                            slot="item"
                            v-model="listQuery.salary"
                            placeholder="选择"
                            clearable
                            @change="handleFilter"
                        >
                            <el-option
                                v-for="item in salary"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </sitem>
                </el-col>
                <el-col :span="6">
                    <sitem label="期望行业：">
                        <el-cascader
                            slot="item"
                            v-model="listQuery.workIndustry"
                            :options="tradeData"
                            @change="handleFilter"
                        />
                    </sitem>
                </el-col>
                <el-col :span="6">
                    <sitem>
                        <el-button
                            slot="item"
                            v-waves
                            class="el-icon-search"
                            type="primary"
                            @click="handleFilter"
                        > 搜索
                        </el-button>
                    </sitem>
                </el-col>
            </el-row>
        </div>

        <div class="mb15">
            <el-popover
                class="ml5"
                placement="bottom-start"
                trigger="hover"
                @show="exportListShow('ADMIN_人才库_导出简历')"
            >
                <el-table
                    :data="exportListData"
                    style="width: 100%"
                    v-loading="popoverLoading"
                >
                    <el-table-column
                        prop="createTime"
                        label="导出时间"
                        width="160"
                    />
                    <el-table-column
                        prop="state_dictText"
                        label="状态"
                    />
                    <el-table-column
                        prop="duration"
                        label="耗时"
                    />
                    <el-table-column
                        label="下载地址"
                        width="310"
                    >
                        <template slot-scope="{row}">
                            <el-link v-if="row.url" type="primary" :href="row.url" target="_blank">
                                {{ row.url.substring(row.url.lastIndexOf('/') + 1) }}
                            </el-link>
                        </template>
                    </el-table-column>

                    <el-table-column
                        prop="duration"
                        label="操作"
                    >
                        <template slot-scope="{row}">
                            <el-popconfirm title="确定删除吗？" @onConfirm="exportDelete(row.id)">
                                <el-button slot="reference" type="danger" size="mini" icon="el-icon-delete" circle/>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button slot="reference" type="primary" icon="el-icon-user" @click="exportResume">导出简历</el-button>
            </el-popover>
            <el-popover
                class="ml5"
                placement="bottom-start"
                trigger="hover"
                @show="exportListShow('ADMIN_人才库_导出名单')"
            >
                <el-table
                    :data="exportListData"
                    v-loading="popoverLoading"
                    style="width: 100%"
                >
                    <el-table-column
                        prop="createTime"
                        label="导出时间"
                        width="160"
                    />
                    <el-table-column
                        prop="state_dictText"
                        label="状态"
                    />
                    <el-table-column
                        prop="duration"
                        label="耗时"
                    />
                    <el-table-column
                        label="下载地址"
                        width="310"
                    >
                        <template slot-scope="{row}">
                            <el-link v-if="row.url" type="primary" :href="row.url" target="_blank">
                                {{ row.url.substring(row.url.lastIndexOf('/') + 1) }}
                            </el-link>
                        </template>
                    </el-table-column>

                    <el-table-column
                        prop="duration"
                        label="操作"
                    >
                        <template slot-scope="{row}">
                            <el-popconfirm title="确定删除吗？" @onConfirm="exportDelete(row.id)">
                                <el-button slot="reference" type="danger" size="mini" icon="el-icon-delete" circle/>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button slot="reference" type="primary" icon="el-icon-user" @click="exportExcel">导出名单</el-button>
            </el-popover>
            <!-- <el-button type="danger" icon="el-icon-document-delete" @click="delMultiple">删除</el-button> -->
        </div>

        <!-- table表格 -->
        <el-table ref="table" :data="list" :stripe="true" style="width: 100%">
            <el-table-column
                type="selection"
                width="55"
            />
            <!-- 序号 -->
            <el-table-column
                type="index"
                width="50"
                label="序号"
                align="center"
            />
            <el-table-column align="center" label="姓名" width="100px">
                <template slot-scope="{ row }">
                    <el-button type="text" @click.native="viewInfo(row)">{{ row.userInfo.name }}</el-button>
                </template>
            </el-table-column>

            <el-table-column align="center" prop="gender" label="性别" width="80px">
                <template slot-scope="{ row }">
                    {{ row.userInfo.sex == 1 ? '男' : '女' }}
                </template>
            </el-table-column>

            <!-- 年龄 -->
            <el-table-column align="center" prop="userInfo.age" label="年龄" width="80px"/>

            <!-- 婚姻状况 -->
            <el-table-column
                align="center"
                label="婚姻状况"
                width="120px"
            >
                <template slot-scope="{ row }">
                    {{ row.userInfo.maritalStatus| maritalStatusFilter }}
                </template>
            </el-table-column>

            <!-- 工作经验/年 -->
            <el-table-column
                align="center"
                prop="userInfo.workYears"
                label="工作经验/年"
                width="120px"
            />

            <!-- 联系方式 -->
            <el-table-column
                align="center"
                prop="userInfo.phone"
                label="联系方式"
                width="150px"
            />

            <!-- 现居地址 -->
            <el-table-column
                align="center"
                prop="userInfo.liveCity_dictText"
                label="现居住地址"
                width="180px"
            />

            <!-- 毕业院校 -->
            <el-table-column
                align="center"
                label="毕业院校"
                width="150px"
            >
                <template slot-scope="{ row }">
                    <template v-if="row.eduInfo.length">
                        {{ row.eduInfo[0].schoolName }}
                    </template>
                </template>
            </el-table-column>

            <!-- 最高学历 -->
            <el-table-column
                align="center"
                label="最高学历"
                width="100px"
            >
                <template slot-scope="{ row }">
                    <template v-if="row.eduInfo.length">
                        {{ row.eduInfo[0].eduLevel | eduLevelFilter }}
                    </template>
                </template>
            </el-table-column>

            <el-table-column
                align="center"
                label="在校时间"
                width="200px"
            >
                <template slot-scope="{ row }">
                    <template v-if="row.eduInfo.length">
                        {{ row.eduInfo[0].startEduTime + '至' + row.eduInfo[0].endEduTime }}
                    </template>
                </template>
            </el-table-column>

            <!-- 政治面貌 -->
            <el-table-column
                align="center"
                prop="userInfo.political"
                label="政治面貌"
                width="150px"
            />

            <!-- 上一家公司 -->
            <el-table-column
                align="center"
                label="当前公司"
                width="100px"
            >
                <template slot-scope="{ row }">
                    <template v-if="row.workInfo.length">
                        {{ row.workInfo[0].companyName }}
                    </template>
                </template>
            </el-table-column>

            <!-- 当前职位 -->
            <el-table-column
                align="center"
                label="当前职位"
                width="100px"
            >
                <template slot-scope="{ row }">
                    <template v-if="row.workInfo.length">
                        {{ row.workInfo[0].positionName_dictText | positionFilter }}
                    </template>
                </template>
            </el-table-column>

            <!-- 期望月薪 -->
            <el-table-column
                align="center"
                label="期望月薪"
                width="200px"
            >
                <template slot-scope="{ row }">
                    {{ row.workIntention|moneyFilter }}
                </template>
            </el-table-column>

            <!-- 期望行业 -->
            <el-table-column
                align="center"
                label="期望行业"
                width="200px"
            >
                <template slot-scope="{ row }">
                    {{ row.workIntention | workIntentionFilter }}
                </template>
            </el-table-column>

            <!-- 证书-->
            <el-table-column
                align="center"
                label="证件"
                width="100px"
            >
                <template slot-scope="{ row }">
                    {{ row.certificateList | certificateFilter }}
                </template>
            </el-table-column>

            <el-table-column
                align="center"
                label="简历更新时间"
                width="200px"
            >
                <template slot-scope="{ row }">
                    {{
                        row.cvResumeList[0].updateTime ? row.cvResumeList[0].updateTime : row.cvResumeList[0].createTime
                    }}
                </template>
            </el-table-column>

            <el-table-column
                align="center"
                label="注册时间"
                width="200px"
            >
                <template slot-scope="{ row }">
                    {{ row.userInfo.createTime }}
                </template>
            </el-table-column>
            <!-- 附件简历 -->
            <!-- <el-table-column align="center" label="附件简历" width="100px">
                    <template slot-scope="{ row }">
                      <span v-if="row.resume === 1">无</span>
                      <el-button v-else type="text">简历</el-button>
                    </template>
                  </el-table-column> -->

            <!-- 职位浏览量-->
            <el-table-column
                align="center"
                prop="browseCount"
                label="职位浏览量"
                width="120px"
            />
            <!-- 投递率-->
            <el-table-column
                align="center"
                label="投递率"
                width="80px"
            >
                <template slot-scope="{ row }">
                    {{ row.deliveryRate * 100 }}%
                </template>
            </el-table-column>
            -->

            <!-- 操作 -->
            <el-table-column label="操作" width="220" fixed="right" align="center">
                <template slot-scope="{row}">
                    <el-button type="text" @click.native="viewInfo(row)">查看简历</el-button>
                    <el-button type="text" @click="downloadResumeByUser(row)">下载简历</el-button>
                    <el-button type="text" @click="disItem(row)">
                        <template v-if="row.banFlag">
                            <span class="el-link el-link--success">启用</span>
                        </template>
                        <template v-else>
                            <span class="el-link el-link--warning">违规禁用</span>
                        </template>
                    </el-button>
                </template>
            </el-table-column>
            <!-- / 操作 -->
        </el-table>
        <!-- / table表格 -->

        <pagination
            v-show="total>0"
            :total="total"
            prev-text="上一页"
            next-text="下一页"
            :page-sizes="[5, 10, 20, 50, 100]"
            layout="prev, pager, next, sizes, jumper"
            :page.sync="listQuerytrue.pageNo"
            :limit.sync="listQuerytrue.pageSize"
            @pagination="getList"
        />

        <pdf-dialog
            ref="pdfDialog"
            @transportShow="transportShow"
            @employShow="employShow"
            @markRes="markRes"
            @interviewShow="interviewShow"
            @refresh="refresh"
        />
        <forward-drawer ref="transportDrawer" @refresh="refresh"/>
        <interview-results-drawer ref="resDrawer" @refresh="refresh"/>
        <interview-drawer ref="interviewDrawer" @refresh="refresh"/>
        <employ-drawer ref="employDrawer" @refresh="refresh"/>
    </el-card>
</template>

<script>
import {cvResumeBan, cvResumeDel, excelGetUserListInfo, getUserListInfo} from '@/api/talent-pool'
import {downloadResumeresume,downloadResumeByUser} from '@/api/common'
import {exportDelete, exportList} from '@/api/export'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import PdfDialog from '@/components/PdfDialog'
import sitem from '@/components/searchItem'
import forwardDrawer from '@/components/CurriculumVitaeStateDrawer/forwardDrawer.vue'
import interviewResultsDrawer from '@/components/CurriculumVitaeStateDrawer/interviewResultsDrawer.vue'
import interviewDrawer from '@/components/CurriculumVitaeStateDrawer/interviewDrawer.vue'
import employDrawer from '@/components/CurriculumVitaeStateDrawer/employDrawer.vue'
import {mapState} from 'vuex'
import {exportFile} from '@/utils/export'
import store from '@/store'

export default {
    name: 'ComplexTable',
    components: {Pagination, PdfDialog, sitem, forwardDrawer, interviewResultsDrawer, interviewDrawer, employDrawer},
    directives: {waves},
    data() {
        return {
            tableKey: 0,
            list: null,
            total: 0,
            listLoading: true,
            popoverLoading:true,
            listQuery: {
                jobName: '',
                userName: '',
                sex: '',
                minAge: '',
                maxAge: '',
                maritalStatus: '',
                experience: '', // 自定义的
                eduLevel: '',
                salary: '', // 自定义的
                workIndustry: ''
            },
            listQuerytrue: {
                pageNo: 1,
                pageSize: 10,
                sort: false,
                minWorkYear: '',
                maxWorkYear: '',
                minMoney: '',
                maxMoney: ''
            },
            tradeData: [], // 行业数据
            exportListData: []
        }
    },
    computed: {
        ...mapState({
            eduLevels: state => state.app.eduLevels,
            sex: state => state.app.sex,
            experience: state => state.app.experience,
            maritalStatus: state => state.app.maritalStatus,
            salary: state => state.app.salary
        })
    },
    filters: {
        maritalStatusFilter(e) {
            switch (e) {
                case 0:
                    return '未婚'
                case 1:
                    return '已婚已育'
                case 2:
                    return '已婚未育'
                case 3:
                    return '离异'
                default:
                    break
            }
        },
        eduLevelFilter(e) {
            switch (e) {
                case 0:
                    return '初中'
                case 1:
                    return '高中'
                case 2:
                    return '中专/中技'
                case 3:
                    return '大专'
                case 4:
                    return '本科'
                case 5:
                    return '硕士'
                case 6:
                    return 'MBA/EMBA'
                case 7:
                    return '博士'
                default:
                    break
            }
        },
        certificateFilter(e) {
            if (!e) return ''
            const certificates = e.map(item => {
                return item.name
            })
            return certificates.join(',')
        },
        workIntentionFilter(e) {
            if (!e) return ''
            const workIndustrys = e.map(item => {
                const d = item.workIndustry_dictText ? item.workIndustry_dictText.split(',') : []
                return d[d.length - 1]
            })
            const newW = Array.from(new Set(workIndustrys))
            return newW.join(',')
        },
        moneyFilter(e) {
            if (!e) return ''
            const moneys = e.map(item => {
                return item.minMoney + '-' + item.maxMoney
            })
            const newM = Array.from(new Set(moneys))
            return newM.join(',')
        },
        positionFilter(e) {
            const arr = e ? e.split(',') : []
            return arr[arr.length - 1]
        }
    },
    async created() {
        this.getList()
        // 行业数据
        if (this.$store.state.app.tradeData.length === 0) {
            const res = await store.dispatch('app/getTrade', 'industry')
            this.tradeData = JSON.parse(JSON.stringify(res.result))
            if (this.tradeData[0].label !== '全部') {
                this.tradeData.unshift({label: '全部', value: ''})
            }
        } else {
            this.tradeData = JSON.parse(JSON.stringify(this.$store.state.app.tradeData))
            if (this.tradeData[0].label !== '全部') {
                this.tradeData.unshift({label: '全部', value: ''})
            }
        }
    },
    methods: {
        exportListShow(from) {
            this.popoverLoading = true
            exportList({from: from}).then(response => {
                this.popoverLoading = false
                if (response.success) {
                    this.exportListData = response.result
                }
            })
        },
        exportDelete(id) {
            exportDelete({id: id}).then(response => {
                if (response.success) {
                    this.$message.success('删除成功')
                } else {
                    this.$message.warning(response.message)
                }
            })
        },
        //下载简历
        downloadResumeByUser(row){
            downloadResumeByUser({users: [row.userInfo.userId].join(',')}).then(response => {
                exportFile(response)
            })
        },
        refresh() {
            this.getList()
            if (this.$refs.pdfDialog.dialogVisible && this.$refs.pdfDialog.showHis) {
                this.$refs.pdfDialog.getList()
            }
        },
        // 查看信息
        viewInfo(row) {
            // row.jobInfo = row.job// 重命名职位信息
            // row.resumeId = row.reId // 重命名简历id
            row.notransport = true
            this.$refs.pdfDialog.show(row, true)
        },
        // 发送简历
        transportShow(e) {
            console.log(e)
            this.$refs.transportDrawer.show(e.name, e.jobName, e.reId)
        },
        // 再次面试
        interviewShow(e) {
            console.log(e)
            this.$refs.interviewDrawer.show(e.name, e.id, e.jobName, e.jobId, e.companyId, e.reId, e.dataId, true) // 最后一个参数 不修改状态
        },
        // 反馈面试结果
        markRes(e) {
            this.$refs.resDrawer.show(e.id, e.userId)
        },
        // 录用
        employShow(e) {
            this.$refs.employDrawer.show(e.name, e.userId, e.jobId, e.componyId, e.id)
        },
        // 分页数据
        getList() {
            this.listLoading = true
            getUserListInfo(this.listQuerytrue).then((response) => {
                this.list = response.result.records
                this.total = response.result.total
                this.listLoading = false
            })
        },
        // 搜索
        handleFilter() {
            this.listQuerytrue.pageNo = 1
            if (this.filterListQuery()) {
                this.getList()
            }
        },
        filterListQuery() {
            const n = this.listQuery
            if (n.experience) {
                this.listQuerytrue.minWorkYear = n.experience.split(',')[0]
                this.listQuerytrue.maxWorkYear = n.experience.split(',')[1]
            } else {
                this.listQuerytrue.minWorkYear = ''
                this.listQuerytrue.maxWorkYear = ''
            }
            if (n.salary) {
                this.listQuerytrue.minMoney = n.salary.split(',')[0]
                this.listQuerytrue.maxMoney = n.salary.split(',')[1]
            } else {
                this.listQuerytrue.minMoney = ''
                this.listQuerytrue.maxMoney = ''
            }
            for (var k in n) {
                this.listQuerytrue[k] = n[k]
            }
            n.workIndustry.length ? this.listQuerytrue.workIndustry = n.workIndustry.join(',') : this.listQuerytrue.workIndustry = ''
            delete this.listQuerytrue.experience
            delete this.listQuerytrue.salary
            if (parseInt(this.listQuerytrue.minAge) > parseInt(this.listQuerytrue.maxAge)) {
                this.$message.error('请填写正确的年龄范围！')
                return false
            }
            return true
        },
        delMultiple() {
            const selected = this.$refs['table'].selection
            var selected_arr = []
            selected.forEach(item => {
                selected_arr.push(item.dataId)
            })
            this.$confirm('此操作将永久删除这些数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.delAction(selected_arr.join(','))
                // this.list.splice(index, 1)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },
        delAction(id) {
            cvResumeDel({id}).then(response => {
                this.$message({
                    type: 'success',
                    message: '保存成功！'
                })
                this.listQuerytrue.pageNo = 1
                this.getList()
            })
        },
        downLoadItem(row) {
            this.exportResumeAction({userId: row.userInfo.userId})
        },
        exportResume() {
            const ids = []
            const selected = this.$refs.table.selection
            selected.forEach(item => {
                ids.push(item.userInfo.userId)
            })
            let parms = null
            if (ids.length) {
                parms = {userId: ids.join(',')}
            } else {
                parms = this.listQuerytrue
                /* this.$message({
                          type: 'error',
                          message: '请勾选要导出的数据！'
                        })
                        return false*/
            }
            parms.from = 'ADMIN_人才库_导出简历'
            this.exportResumeAction(parms)
        },
        exportResumeAction(parms) {
            downloadResumeresume(parms).then(response => {
                if (response.success) {
                    this.$message.success('任务建立成功')
                    this.exportListShow(parms.from)
                } else {
                    this.$message.error('任务建立失败')
                }
            })
        },
        exportExcel() {
            const ids = []
            const selected = this.$refs.table.selection
            selected.forEach(item => {
                ids.push(item.dataId)
            })
            let parms = null
            if (ids.length) {
                parms = {dataId: ids.join(',')}
            } else {
                this.filterListQuery()
                parms = this.listQuerytrue
            }
            parms.from = 'ADMIN_人才库_导出名单'
            excelGetUserListInfo(parms).then(response => {
                if (response.success) {
                    this.$message.success('任务建立成功')
                    this.exportListShow(parms.from)
                } else {
                    this.$message.error('任务建立失败')
                }
                // exportFile(response)
            })
        },
        // 禁用
        disItem(rowData) {
            this.$confirm('确定要' + (rowData.banFlag ? '启用' : '禁用') + '此用户吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                cvResumeBan({userId: rowData.userInfo.userId}).then(response => {
                    this.$message({
                        type: 'success',
                        message: rowData.banFlag ? '已启用!' : '已禁用！'
                    })
                    this.handleFilter()
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                })
            })
        }
    }
}
</script>
<style lang="scss" scoped>
.operation {
    cursor: pointer;
}
</style>
